import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Tools, Button, Icon, Modal, Bubble } from 'weaver-mobile';

import { TitleUtil } from '../../util';
import Api from '../../apis/setting';

import TableList from './tableList';
import AddMailAccount from './addMailAccount';

const alert = Modal.alert;
const { getLabel } = Tools;
const noop = () => { }

@inject('mailAccountStore')
@withRouter
@observer
export default class MailAccount extends Component {
  constructor(props){
    super(props);
    this.state = {
      page: ''
    }
  }
  componentDidMount() {
    const { mailAccountStore, title } = this.props;
    const { form } = mailAccountStore;
    title && TitleUtil.setTitle(title);
    // 表单信息
    Api.getEmailAccountCondition().then(res => {
      const { conditioninfo } = res;
      form.initForm(conditioninfo, '/setting/mailAccount/addMailAccount/form');
    });
  }

  componentWillReceiveProps(nextProps) {
    const { title } = this.props;
    if (nextProps.path === nextProps.location.pathname) {
      TitleUtil.setTitle(title);
    }
  }

  editInfo = (params) => {
    const { history, mailAccountStore, mailAccountStore: { form } } = this.props;
    if (params) {
      this.setState({page: 'edit'},()=>{
        const { data: { randomFieldId } } = params;
        Api.getMailAccountBean({ id: randomFieldId }).then(res => {
          const { status, emailAccountBean } = res;
          if (Number(status)) {
            mailAccountStore.setState({ accountId: randomFieldId });
            let fields = {};
            Object.keys(emailAccountBean).forEach(domkey => {
              if (domkey === 'sentItems') { // sentItems修改数据格式，单独处理
                let sentItemsVal = []
                if (emailAccountBean[domkey]) {
                  emailAccountBean[domkey].split(',').forEach((item, index) => {
                    sentItemsVal = [...sentItemsVal, {id: String(index), name: item, validate: true}]
                  })
                }
                mailAccountStore.setState({ sentItemsVal })
              } 
              fields = { ...fields, [domkey]: { value: emailAccountBean[domkey] } };
            });
            form.updateFields(fields);
          }
        });
      })
    } else {
      this.setState({page: 'account'},()=>{
        mailAccountStore.setState({ accountId: '' });
        form.resetFields();
      })
    }
    history.push('/setting/mailAccount/addMailAccount');
  }

  deleteAccount = (params) => {
    alert(getLabel('81509', '删除邮件账户会删除账户下的邮件，确认删除？'), '', [
      { text: getLabel('31129', '取消') },
      { text: getLabel('826', '确定'), onPress: () => {
        const { mailAccountStore: { tableListStore } } = this.props;
        const { data: { randomFieldId } } = params;
        Api.deleteUserMailAccount({ mailAccountIDs: randomFieldId }).then(res => {
          const { flag, message } = res;
          if (flag) {
            tableListStore.refreshTableList();
          } else {
            Bubble.error(message, 1, { top: '50%' });
          }
        });
      }},
    ]);
  }

  renderOps = (o, check, data) => {
    const index = Number(o.index);
    let handler = noop;
    let icon = '';
    if (o.index * 1 === 0) {
      handler = this.editInfo;
      icon = 'bianji';
    } else if (o.index * 1 === 1) {
      handler = this.deleteAccount;
      icon = 'delete';
    }
    return (
      <span
        onClick={() => handler({ params: check[`randomFieldOpPara${index}`], data })}
        key={o.index}
        style={{ marginRight: 5 }}
      >
        {icon && <Icon type={icon}/>}
        {o.text}
      </span>
    );
  }

  render() {
    const { history, mailAccountStore } = this.props;
    const { tableListStore, form, accountId } = mailAccountStore;
    return (
      <div className="mailAccount">
        <Button className="btn-add" icon="open" onClick={() => { this.editInfo(); history.push('/setting/mailAccount/addMailAccount'); }}>{getLabel('384433', '新建账户信息')}</Button>
        <TableList store={tableListStore} renderTitle={data => data.accountName} renderOps={this.renderOps}/>
        <Route
          key="addMailAccount"
          path="/setting/mailAccount/addMailAccount"
          render={() => (<AddMailAccount accountId={accountId} form={form} from={this.state.page} />)}
        />
      </div>
    );
  }
}

